// pages/appointment/appointment.js
const APP = getApp()
var util = require('../../utils/util')
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		subscribeType: [], //预约类型

		userInfo: null,
		showStep: false,
		showChoosePrison: false, //展示显示监狱
		timeRangeSelecter: [], //  可选时间范围数组
		daySelecter: [], //可选日期数组
		// jianyuList: [], //可选监狱列表
		deptId: '', //监狱id
		personList: [], //可选监狱会见人列表
		columns: ['张三', '李四', '王五', '纪晓岚', '关羽'],
		radio: '1', //单选框
		showChooseDialog: false, //会见人多选框对话框
		visible: false, //气泡
		// yuyueTimes: ['10.00-20.00', '10.00-20.00', '10.00-20.00', '10.00-20.00', '10.00-20.00', '10.00-20.00'], // 预约时间段
		yuyueForm: {
			deptId: '', //监狱id
			timeDateStr: '', //时间段
			timeDate: '', //日期
			name: '', //姓名
			card: '', //身份证号
			prison: '', //所在监区
			remark: '',
			ids: [],
			subscribeType: '', //预约类型      
			attorney: '', //事务所
			office: '', //委托书
		},
		fileListAttorneyImage: [],
		fileListOfficeImage: [],
		api: util.config().api + '/mobileUser/common/upload',
		peopleOptions: [], //拿到的预约人标签列表  不是他们的id id在  yuyueForm.ids
		prisons: [], //监区列表
		deptId: '', //单个监狱 点击监狱获取的deptId
		jianyuActiveIndex: -1,
		timeActiveIndex: -1, //时间选择下标
		jianyuList: [], //可选监狱列表
		current: 0, //步骤条下标
		showTime: false, //请选择预约日期 时间段 弹窗
		show1: false,
		show2: false,
		show3: false,
		value1: '广西',
		value2: '',
		value3: '',
		code1: '',
		// 140000
		code2: '',
		code3: '',
		options1: [], //省
		options2: [], // 市
		options3: [], // 区
		areaList: {
			province_list: {
				// //省
			},
			city_list: {
				// // 市
			},
			county_list: {
				// // 区
			}
		},
		noticeId: null,
	},
	// 上传前校验
	beforeRead(event) {
		const {
			file,
			callback
		} = event.detail;
		callback(file.type === 'image');
	},


	// 删除 所函
	deleteReadAttorneyImage() {
		this.setData({
			fileListAttorneyImage: [],
			'yuyueForm.attorney': ''
		})
	},
	// 删除 委托书
	deleteReadOfficeImage() {
		this.setData({
			fileListOfficeImage: [],
			'yuyueForm.office': ''
		})
	},
	// 上传后校验    所函
	afterReadAttorneyImage(event) {
		let that = this
		const {
			file
		} = event.detail;
		console.log(file);

		wx.uploadFile({
			url: that.data.api, // 仅为示例，非真实的接口地址
			filePath: file.path,
			name: 'file',
			formData: {
				user: 'test'
			},
			success(res) {
				// 上传完成需要更新 fileList
				var data = JSON.parse(res.data)
				console.log('图片上传服务器返回值', data)
				var fileList = []
				fileList.push(data)
				that.setData({
					fileListAttorneyImage: fileList,
					'yuyueForm.attorney': data.fileName
				});
			},
		});
	},
	// 上传后校验    委托书
	afterReadOfficeImage(event) {
		let that = this
		const {
			file
		} = event.detail;
		console.log(file);

		wx.uploadFile({
			url: that.data.api, // 仅为示例，非真实的接口地址
			filePath: file.path,
			name: 'file',
			formData: {
				user: 'test'
			},
			success(res) {
				// 上传完成需要更新 fileList
				var data = JSON.parse(res.data)
				console.log('图片上传服务器返回值', data)
				var fileList = []
				fileList.push(data)
				that.setData({
					fileListOfficeImage: fileList,
					'yuyueForm.office': data.fileName
				});
			},
		});
	},
	// 类型onChangeRadio  切换
	onChangeRadio(event) {
		console.log(event.detail);

		this.setData({
			"yuyueForm.subscribeType": event.detail,
		});
		console.log('yuyueForm.subscribeType', this.data.yuyueForm.subscribeType);
		console.log('event.detail', event.detail);
	},
	//预约人信息   关闭标签
	closeTag(e) {
		// console.log(e)
		var index = e.currentTarget.dataset.index
		// console.log(index)
		var peopleOptions = this.data.peopleOptions
		peopleOptions.splice(index, 1);
		this.setData({
			peopleOptions: peopleOptions
		})
	},
	// 选择监狱  确认
	onChooseprisonsConfirm(e) {
		const {
			picker,
			value,
			index
		} = e.detail;
		this.setData({
			'yuyueForm.prison': value
		})
		this.onClose()
	},
	// 点击所在监区  打开选择监区的picker
	choosePrisons() {
		// console.log('111111')
		this.setData({
			showChoosePrison: true
		})
	},
	// getPerson  获取会见人列表
	getPerson() {
		this.setData({
			personList: [],
		})
		var postObj = {
			url: '/mobileUser/subscribe/getPerson/' + this.data.deptId,
			method: 'get',
		}

		APP.request.wxRequest(postObj).then(res => {

			if (res.data.code === 200) {
				console.log('获取可选会见人列表', res)
				var data = res.data.rows
				data.forEach((items, i) => {
					items.text = items.name
				})
				this.setData({
					personList: res.data.rows
				})

				// 展示会见人对话框
				this.setData({
					showChooseDialog: true
				})
			}
		})
	},


	//监听值变化  表单输入信息
	onChange(e) {
		var formName = e.target.dataset.formname
		var name = `yuyueForm.${formName}`;
		this.setData({
			[name]: e.detail
		})
		console.log(formName)
	},


	// 选择会见人的取消
	onChooseCancel() {
		this.onClose()
	},
	// 选择会见人的确定
	onChooseConfirm(e) {
		// yuyueForm: {
		//   deptId: '', //监狱id
		//   timeDateStr: '', //时间段
		//   timeDate: '', //日期
		//   name: '', //姓名
		//   card: '', //身份证号
		//   prison: '', //所在监区
		//   remark: '',
		//   ids: []
		// },
		const {
			picker,
			value,
			index
		} = e.detail;
		// console.log(picker, value, index)

		if (!!value) {
			this.setData({
				'yuyueForm.name': value.name,
				'yuyueForm.card': value.card,
				'yuyueForm.prison': value.prison
			})
		}
		this.onClose()
	},


	// 点击单个监狱     获取deptid
	clickItems(e) {
		this.setData({
			'yuyueForm.timeDate': '',
			'yuyueForm.timeDateStr': '',
		})
		var index = e.target.dataset.index
		console.log('当前监狱信息', this.data.jianyuList[index]);
		console.log('当前监狱监区', this.data.jianyuList[index].prisons);

		if (!!this.data.jianyuList[index].prisons) {
			var prisons = this.data.jianyuList[index].prisons
			var myStr = new Array() //定义一数组
			if (!!prisons) myStr = prisons.split(';') //字符分割
			this.setData({
				prisons: [],
			})
			this.setData({
				prisons: this.data.prisons.concat(myStr)
			})

			// myStr.forEach((items, i) => {
			//   // this.prisons.push(items)
			//   var thisprisons = this.data.prisons
			//   thisprisons.push(items)
			//   this.setData({
			//     prisons: thisprisons
			//   })
			// })

			var deptId = this.data.jianyuList[index].deptId
			this.setData({
				deptId: deptId
			})
			console.log('监区列表', this.data.prisons);

		}
		//点击下标赋值
		this.setData({
			jianyuActiveIndex: index
		})
		//  根据deptId    获取监狱可以预约的时间
		// 
		var postObj = {
			url: '/mobileUser/subscribe/getTime/' + this.data.deptId,
			method: 'get',
		}

		APP.request.wxRequest(postObj).then(res => {
			console.log('获取监狱可以预约的时间', res)
			var daySelecter = res.data.data
			this.setData({
				daySelecter: daySelecter
			})
		})
	},
	// 格式化时间
	formatDate(date) {
		// date.bottomInfo = '选中';
		var month = date.getMonth() + 1
		if (+month < 10) {
			month = '0' + month
		}
		var day = date.getDate()
		console.log(day);

		if (+day < 10) {
			day = '0' + day
		}
		// return `${date.getFullYear()}-${month}-${date.getDate()}`;
		return `${date.getFullYear()}-${month}-${day}`;

	},
	//openDay    监听打开事件  打开日历组件
	openDay() {
		this.setData({
			timeRangeSelecter: [],
			timeActiveIndex: -1,
			'yuyueForm.timeDateStr': ''
		})
	},
	// 点击日期选择器的日期     做显示可选时间段范围判断
	selectDay(e) {
		this.setData({
			timeRangeSelecter: []
		})
		console.log('日期格式化', this.formatDate(e.detail))
		this.setData({
			'yuyueForm.timeDate': this.formatDate(e.detail),
			'yuyueForm.deptId': this.data.deptId
		})
		var date = this.formatDate(e.detail)
		var daySelecter = this.data.daySelecter
		// console.log(date);
		console.log(daySelecter);

		// 遍历  把时间一致的日期范围数据放到
		daySelecter.forEach((items, i) => {
			if (items.timeDateStr == date) {
				console.log(items.times)
				this.setData({
					timeActiveIndex: -1,
					'yuyueForm.timeDateStr': '',
					timeRangeSelecter: items.times
				})
			}
		})
		console.log('日期范围数据', this.data.timeRangeSelecter);

	},
	//点击日期选择器的时间
	clickTime(e) {
		var index = e.target.dataset.index
		console.log(this.data.timeRangeSelecter[index]);

		this.setData({
			timeActiveIndex: index,
			'yuyueForm.timeDateStr': this.data.timeRangeSelecter[index].timeDateStr,
			'yuyueForm.recoderId': this.data.timeRangeSelecter[index].recoderId
		})

	},


	// 请求 省数据  请求成功打开省弹窗
	showPopup1() {
		wx.removeStorage({
			key: 'peopleOptions',
		})
		this.setData({
			peopleOptions: [],
			'areaList.province_list': {},
		})
		var postObj = {
			url: '/mobileUser/subscribe/queryProvince',
			method: 'get',
			data: ''
		}

		APP.request.wxRequest(postObj).then(res => {
			console.log('省', res.data.data)
			this.setData({
				options1: res.data.data
			})

			var options1 = this.data.options1

			var objList = {}
			options1.forEach((items, i) => {
				var obj = APP.transformObject(items.areaId, items.name)
				// var guangxi = {450000: "广西"}
				objList = {
					// ...guangxi,
					...objList,
					...obj
				}
			})

			console.log(objList);


			this.setData({
				show1: true,
				show2: false,
				show3: false,
				'areaList.province_list': objList,
				//同时要把市 区的数据清空
				// value1: '',
				// value2: '',
				// value3: '',
				// options2: [], // 市
				// options3: [], // 区
				//  // 'areaList.province_list': {},
				// 'areaList.city_list': {},
				// 'areaList.county_list': {},
				deptId: '',
				// jianyuList: [],
				jianyuActiveIndex: -1,
				prisons: [],
				deptId: '',
				daySelecter: [],
				timeRangeSelecter: [],
				'yuyueForm.deptId': ''
			})
		})

		{
			//  选择省确认时候同时选择市  市接口请求
			// var data
			// if (this.data.value1 == 450000) {
			//   data = {
			//     areaId: 450000
			//   }
			// } else {

			// }
			var data = (this.data.value1 == '广西') ? {
				areaId: 450000
			} : {
				areaId: this.data.code1
			}

			var postObj = {
				url: '/mobileUser/subscribe/queryCity',
				method: 'get',
				data: data
				// data: {
				//   areaId: 450000
				// }
			}
			APP.request.wxRequest(postObj).then(res => {
				console.log('市', res.data.data)

				this.setData({
					options2: res.data.data
				})
				var options2 = this.data.options2
				var objList2 = {}
				options2.forEach((items, i) => {
					var obj = APP.transformObject(items.areaId, items.name)
					objList2 = {
						...objList2,
						...obj
					}
				})
				this.setData({
					'areaList.city_list': objList2,
				})
			})

		}
	},

	// 请选择预约日期 时间段 弹窗
	showTime() {
		this.setData({
			show: false,
			showTime: true
		});
	},
	// 关闭省市区弹窗
	onClose() {
		this.setData({
			show1: false,
			show2: false,
			show3: false,
			showTime: false,
			showChooseDialog: false,
			showChoosePrison: false,
		});
	},
	// 选择事件
	// 确认 省  点击省的确认  请求市
	confirm1(e) {
		// console.log(e);
		// this.setData({
		//   value1: e.detail.values[0].name
		// })

		console.log(this.data.areaList);


		this.onClose()

	},
	cancel1(e) {
		console.log(e);
		this.onClose()
	},
	//省市区监听值改变
	change1(e) {
		console.log(e);
		this.setData({
			jianyuList: [],
		})
		var values = e.detail.values
		var name1 = e.detail.values[0].name
		var areaId1 = e.detail.values[0].code
		console.log('省areaId', areaId1)
		// 省areaId 存在  请求市接口
		if (!!areaId1) {
			//  选择省确认时候同时选择市  市接口请求
			var postObj = {
				url: '/mobileUser/subscribe/queryCity',
				method: 'get',
				data: {
					areaId: areaId1,
				}
			}
			APP.request.wxRequest(postObj).then(res => {
				console.log('市', res.data.data)

				this.setData({
					options2: res.data.data
				})
				var options2 = this.data.options2
				var objList2 = {}
				options2.forEach((items, i) => {
					var obj = APP.transformObject(items.areaId, items.name)
					objList2 = {
						...objList2,
						...obj
					}
				})
				this.setData({
					'areaList.city_list': objList2,
				})
			})
		}

		var name2 = ''
		var areaId2 = ''
		if (!!e.detail.values[1]) {
			name2 = e.detail.values[1].name
			areaId2 = e.detail.values[1].code
			console.log('市areaId', areaId2)
		}
		// 市areaId 存在  请求区接口
		if (!!areaId2) {
			//  选择市确认时候同时选择区  区接口请求
			var postObj = {
				url: '/mobileUser/subscribe/queryArea',
				method: 'get',
				data: {
					areaId: areaId2
				}
			}
			APP.request.wxRequest(postObj).then(res => {
				console.log('区', res.data.data)

				this.setData({
					options3: res.data.data
				})
				var options3 = this.data.options3
				var objList3 = {}
				options3.forEach((items, i) => {
					var obj = APP.transformObject(items.areaId, items.name)
					objList3 = {
						...objList3,
						...obj
					}
				})
				this.setData({
					'areaList.county_list': objList3,
				})
			})
		}

		var name3 = ''
		var areaId3 = ''
		if (!!e.detail.values[2]) {
			name3 = e.detail.values[2].name
			areaId3 = e.detail.values[2].code
			console.log('市areaId', areaId3)
		}


		// 省市区赋值
		this.setData({
			value1: name1,
			value2: name2,
			value3: name3,
			code1: areaId1,
			code2: areaId2,
			code3: areaId3,
		})

		// 区areaId 存在  遍历拿到 监狱列表
		// var deptId = ''
		if (!!e.detail.values[2]) {
			var code3 = e.detail.values[2].code

			var postObj = {
				url: '/mobileUser/subscribe/getDept/' + code3 + '/' + this.data.noticeId,
				method: 'get',
				data: ''
			}

			APP.request.wxRequest(postObj).then(res => {
				console.log('监狱列表', res.data.data)
				this.setData({
					jianyuList: res.data.data
				})
			})


		}





	},
	// 点击上一步
	back() {
		const redCurrent = this.data.current - 1;
		const current = redCurrent == 0 ? 0 : addCurrent;
		this.setData({
			'current': current
		})
	},
	// 点击下一步
	next() {

		// yuyueForm: {
		//   deptId: '', //监狱id
		//   timeDateStr: '', //时间段
		//   timeDate: '', //日期
		//   name: '', //姓名
		//   card: '', //身份证号
		//   prison: '', //所在监区
		//   remark: '',
		//   ids: []
		// },

		var addCurrent = this.data.current
		if (addCurrent == 0) {
			if (!!!this.data.yuyueForm.deptId) {
				wx.showToast({
					title: '信息补全！',
					image: '../../assets/error.png',
				})
			} else if (!!!this.data.yuyueForm.timeDateStr) {
				wx.showToast({
					title: '未选时间段！',
					image: '../../assets/error.png',
				})
			} else if (!!!this.data.yuyueForm.timeDate) {
				wx.showToast({
					title: '未选日期！',
					image: '../../assets/error.png',
				})
			} else {
				addCurrent = this.data.current + 1;
				var current = addCurrent > 2 ? 2 : addCurrent;
				this.setData({
					'current': current
				})
			}
		} else if (addCurrent == 1) {
			// 预约人信息  ids  赋值
			var peopleOptions = this.data.peopleOptions
			if (peopleOptions.length > 0) {
				var ids = []
				peopleOptions.forEach((items, i) => {
					ids.push(items.interviewerId)
				})
				this.setData({
					'yuyueForm.ids': ids
				})
			}
			console.log(this.data.yuyueForm.ids);
			var reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
			if (!this.data.yuyueForm.name) {
				wx.showToast({
					title: '未选会见人！',
					image: '../../assets/error.png',
				})
			} else if (!this.data.yuyueForm.card) {
				wx.showToast({
					title: '输入身份证！',
					image: '../../assets/error.png',
				})
			} else if (!(this.data.yuyueForm.card.match(reg))) {
				wx.showToast({
					title: '身份证不正确！',
					image: '../../assets/error.png',
				})
			} else if (!this.data.yuyueForm.remark) {
				wx.showToast({
					title: '输入会见理由！',
					image: '../../assets/error.png',
				})
			}
			// else if (this.data.yuyueForm.ids.length < 1) {
			// 	wx.showToast({
			// 		title: '未选会见人！',
			// 		image: '../../assets/error.png',
			// 	})
			// } 
			else if (this.data.userInfo.type == '2' && !this.data.yuyueForm.attorney) {
				wx.showToast({
					title: '事务所所函！',
					image: '../../assets/error.png',
				})
			} else if (this.data.userInfo.type == '2' && !this.data.yuyueForm.office) {
				wx.showToast({
					title: '委托书/公函！',
					image: '../../assets/error.png',
				})
			} else {

				// 新增预约的请求
				// POST/mobileUser/subscribe/add
				var postObj = {
					url: '/mobileUser/subscribe/add',
					method: 'post',
					data: this.data.yuyueForm
				}


				APP.request.wxRequest(postObj).then(res => {
					if (res.data.code === 200) {
						addCurrent = this.data.current + 1;
						var current = addCurrent > 2 ? 2 : addCurrent;
						this.setData({
							'current': current
						})
					} else {
						wx.showToast({
							title: '请求失败',
							image: '../../assets/error.png',
						})
					}

				})
			}

		} else {
			addCurrent = this.data.current + 1;
			var current = addCurrent > 2 ? 2 : addCurrent;
			this.setData({
				'current': current
			})
		}
	},
	// 去返回首页
	toLoginIndexReLaunch() {
		this.setData({
			showStep: true,
		})
		APP.toLoginIndexReLaunch()
	},
	// 去我的预约
	toMyAppointmentReLaunch() {
		this.setData({
			showStep: true,
		})
		APP.toMyAppointmentReLaunch()
	},
	//跳转到添加预约人
	toAddAppoPeopleNavigate() {
		console.log(11)
		wx.navigateTo({
			url: '/pages/addAppoPeople/addAppoPeople',
		})
	},

	// 市
	showPopup2() {
		this.setData({
			show1: false,
			show2: true,
			show3: false,
		})
	},
	// 区
	showPopup3() {
		this.setData({
			show1: false,
			show2: false,
			show3: true,
		})
	},
	//
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let that = this
		that.setData({
			noticeId: options.noticeId
		})
		// 律师 家属   类型字典
		APP.getDict('sys_mobile_user_type').then(res => {
			console.log('用户类型字典', res)
			// this.setData({
			//   userType: res.data.data
			// })
		})
		//预约类型字典
		APP.getDict('sys_subscribe_type').then(res => {
			console.log('预约类型字典', res)

			that.setData({
				subscribeType: res.data.data,
				"yuyueForm.subscribeType": res.data.data[1].dictValue,
			})
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		let that = this



		APP.getFrontInfo().then(res => {
			var userInfo = res.data.data
			that.setData({
				userInfo: userInfo
			})
			console.log('用户信息', that.data.userInfo)
		})
		//获取本地getStorage  peopleOptions  数组
		// var peopleOptions = JSON.parse(wx.getStorage('peopleOptions'))
		// console.log('获取本地peopleOptions', peopleOptions)
		wx.getStorage({
			key: 'peopleOptions',
			success: (res) => {
				var data = JSON.parse(res.data)
				that.setData({
					peopleOptions: data
				})
				console.log('获取本地peopleOptions', that.data.peopleOptions)
			}
		})

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})